package behavioral_pattern.Interpreter_pattern;

import java.util.Stack;

public class InstructionHandler {
    private AbstractMode node;

    public void handle(String instruction) {
        AbstractMode left = null, right = null;
        AbstractMode direction = null, action = null, distance = null;
        Stack stack = new Stack();
        String [] words = instruction.split(" "); //指令操作符以空格分开
        System.out.println("输入指令："+instruction);
        for (int i = 0; i < words.length; i++) {
            System.out.println("指令："+words[i]);
            if (words[i].equalsIgnoreCase("and")){
                left = (AbstractMode) stack.pop();
                String word = words[++i];
                direction = new DirectionNode(word);
                String word1 = words[++i];
                action = new ActionNode(word1);
                String word2 = words[++i];
                distance = new DistanceNode(word2);
                right = new SentenceNode(direction,action,distance);
                stack.push(new AndNode(left,right));
            }else {
                String word = words[i];
                direction = new DirectionNode(word);
                String word1 = words[++i];
                action = new ActionNode(word1);
                String word2 = words[++i];
                distance = new DistanceNode(word2);
                left = new SentenceNode(direction,action,distance);
                stack.push(left);
            }
        }
        this.node = (AbstractMode) stack.pop();
    }

    public String output(){
        String interpret = node.interpret();
        return interpret;
    }
}
